<template>
    <div class="competition-table" id="handlePrint">
        <h2>{{ title }}</h2>
        <el-table :data="tableData" border style="width: 100%;">
            <el-table-column prop="id" label="序号" width="50" header-class-name="custom-header" />
            <el-table-column prop="userName" label="姓名" />
            <el-table-column prop="sex" label="性别" width="40" />
            <el-table-column :label="'组别'">
                <template #default="{ row }">
                    {{ getGroupName(row.matchesGroupId) }}
                </template>
            </el-table-column>
            <el-table-column :label="'单位'">
                <template #default="{ row }">
                    {{ getTeamName(row.teamGroupId) }}
                </template>
            </el-table-column>
            <el-table-column :label="'项目'">
                <template #default="{ row }">
                    {{ getProjectName(row.projectId) }}
                </template>
            </el-table-column>
            <!-- 假设每个项目有18个可能的评分项 -->
            <el-table-column v-for="(scoreObj, index) in getScoresColumns(numbers)" :key="index"
                :label="'评分与编码' + (index + 1)" header-class-name="custom-header">
                <template #default="{ row }">
                    <div v-if="row.codeName[index] && row.codeName[index].code" class="show-overflow-tooltip">
                        <!-- 显示评分和编码 -->
                        {{ row.codeName[index].code || '-' }} ({{ row.codeName[index].score || '-' }})
                    </div>
                    <div v-else>
                        -
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="totalScore" label="总分" width="100" />
        </el-table>

        <el-button type="primary" v-print="printConfig" class="print-button-container">打印</el-button>
        <el-button type="primary" @click="handleCancel" class="print-button-container">取消</el-button>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

const route = useRoute();
const router = useRouter();

const id = route.query.matchid;
const teamId = route.query.teamid;
const token = localStorage.getItem('userToken');

const matchteamid = ref([]);
const matchprojectid = ref([]);
const matchgroupid = ref([]);

// 映射对象
const groupMap = ref({});
const teamMap = ref({});
const projectMap = ref({});

const title = ref('');

// 表格数据
const tableData = ref([]);


const numbers = ref('');
//获取比赛名称
async function fetchmatch() {
    try {
        const response = await axios.get(`http://back1.idcfengye.com:15173/competition/match/${id}`);
        const matchname = response.data.match;
        matchname.map(match => {
            title.value = match.title;
        });
    } catch (error) {
        console.log(error);
    }
}

fetchmatch();



// 辅助函数：解析并计算分数
function parseAndSumScores(scoreStr) {
    if (!scoreStr) return 0;
    const scores = scoreStr.split('+').map(Number);
    return scores.reduce((sum, score) => sum + (isNaN(score) ? 0 : score), 0);
}

// 预处理数据
function preprocessData(data) {
    const processedData = [];

    data.forEach(athlete => {
        athlete.codes.forEach((code, index) => {
            const score = code.codes;
            // 解析并计算每个评分项的分数
            const fen = score.map((scoreObj, idx) => {
                if (scoreObj && scoreObj.score) {
                    const scoreid = parseAndSumScores(scoreObj.score);
                    return scoreid;
                }
                return
            });

            const zongfen = fen.reduce((sum, current) => sum + current, 0);

            // 创建一个新对象，包含运动员的基本信息和当前项目的评分及编码信息
            const newData = {
                ...athlete,
                projectId: code.projectId,
                totalScore: zongfen.toFixed(3), // 将总分数保留三位小数
                codeName: score,
                scores: Array(numbers.value).fill({ score: null, codeName: code.codeName }) // 初始化评分数组，包含codeName
            };
            // 删除原始的codes数组，因为我们已经将其信息分散到了scores和codeName中

            delete newData.codes;

            processedData.push(newData);
        });
    });

    return processedData;
}

// 处理取消按钮
function handleCancel() {
    router.push({ path: '/home/personnel', query: { id: id } });
}

//通过比赛的matchid获取本比赛的组别
async function matchgroup() {
    const matchid = id
    try {
        const response = await axios.get(`http://back1.idcfengye.com:15173/competition/matchgroup/${matchid}`, {
            headers: {
                'Authorization': 'Bearer ' + token
            }
        });
        matchgroupid.value = response.data.matchgroup;
    } catch (error) {
        console.log(error);
    }
}

matchgroup();

//通过比赛的matchid获取本比赛的所有项目
async function matchproject() {
    const matchid = id
    try {
        const response = await axios.get(`http://back1.idcfengye.com:15173/competition/project/${matchid}`, {
            headers: {
                'Authorization': 'Bearer ' + token
            }
        })
        matchprojectid.value = response.data.project;
    } catch (error) {
        console.log(error);
    }
}

matchproject();

// 填充映射对象
function populateMaps() {
    matchgroupid.value.forEach(group => {
        groupMap.value[group.id] = group.groupname;
    });

    teamMap.value[matchteamid.value.id] = matchteamid.value.teamName;

    matchprojectid.value.forEach(project => {
        projectMap.value[project.id] = project.projectName;
    });
}

// 获取matchid对应项目
async function matchteam() {
    try {
        const response = await axios.get(`http://back1.idcfengye.com:15173/competition/teamgroup/${teamId}`, {
            headers: { 'Authorization': 'Bearer ' + token },
        });
        matchteamid.value = response.data.teamGroup || [];
    } catch (error) {
        console.error('未找到对应项目:', error);
    }
}

matchteam();

// 在获取数据后调用
async function initializeData() {
    await matchteam();
    await matchgroup();
    await matchproject();
    populateMaps();
}

initializeData();


// 辅助函数：获取映射后的名称
function getGroupName(groupId) {
    return groupMap.value[groupId] || '-';
}

function getTeamName(teamId) {
    return teamMap.value[teamId] || '-';
}

function getProjectName(projectId) {
    return projectMap.value[projectId] || '-';
}


// 处理打印
const printConfig = {
    id: 'handlePrint',
    extraCss: 'https://cdn.example.com/print-style1.css, https://cdn.example.com/print-style2.css', // 逗号分隔的CSS文件路径字符串
    // 其他配置...
};

// 获取成员信息
async function handleTeamChange() {
    try {
        const response = await axios.get(
            `http://back1.idcfengye.com:15173/teamproject/staff/routine/${teamId}`,
            {
                headers: {
                    'Authorization': 'Bearer ' + token,
                },
            }
        );
        console.log(response.data);

        const processedData = preprocessData(response.data.data);
        tableData.value = processedData;
        const count = response.data.data;
        const maxLengths = count.map(item => {
            const codes = item.codes;
            // 使用 reduce 方法找到每个 item 的 codes 最大长度
            return codes.reduce((max, code) => Math.max(max, code.codes.length), 0);
        });
        
        // 使用 Math.max 和 apply 方法从 maxLengths 数组中找到最大值
        numbers.value = Math.max(...maxLengths);

    } catch (error) {
        console.error('没有找到团队', error);
    }
}

// Helper function to generate column labels for scores
function getScoresColumns(count) {
    return Array.from({ length: count }, (_, i) => i + 1);
}
onMounted(() => {
    handleTeamChange();
})
</script>

<style scoped>
.competition-table {
    text-align: center;
    margin: 0 auto;
    /* 使表格居中 */
    max-width: 100%;
    /* 确保表格不超过容器宽度 */
}

.print-button-container {
    width: 100px;
    margin-left: 48%;
    margin-top: 10px;
}

@media print {

    .el-select,
    .el-button,
    .print-button-container {
        display: none;
        /* 隐藏下拉框和按钮 */
    }

    .competition-table {
        width: 100%;
        /* 确保表格在打印时宽度为100% */
    }
}

.show-overflow-tooltip {
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 隐藏溢出部分 */
    text-overflow: ellipsis;
    /* 使用省略号显示溢出文本 */
}

::v-deep .el-table th.custom-header.cell {
    white-space: nowrap !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
}
</style>